package com.ivo.quartz;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.ivo.biz.OperationForeman;
import com.ivo.biz.OperationForemanManager;
import com.ivo.sys.Code;
import com.ivo.sys.CodeService;

/**
 * 
 *
 * @author Minkey Wang
 * @version 2018年2月22日
 */
@Repository
public class ForemanQuartz {
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
    
	@Autowired
	private CodeService codeService;
	
	@Autowired
	private OperationForemanManager operationForemanManager;
	
	@Transactional
    @Scheduled(cron = "0 35 6 16 * ? ")//每月16日上午06:35触发
	public void execute() {
		
	    RestTemplate restTemplate = new RestTemplate();
	    Gson googleJson = new Gson();
	    JsonParser parser = new JsonParser();
		//同步站点和领班、课的关系
		
		logger.info("同步站点和领班start");
		//先将所有的数据置为无效
		operationForemanManager.deleteAll();
		String shipurl = "http://myivo.ivo.com.cn/FHR/restful/manager.do";
		String shipjson = restTemplate.getForObject(shipurl, String.class);
		JsonArray shipJarray   = parser.parse(shipjson).getAsJsonArray();
		List<Operation> jsonShipList =  googleJson.fromJson(shipJarray, new TypeToken<List<Operation>>() { }.getType());
		for(Operation operation:jsonShipList){
				OperationForeman opeForeman=new OperationForeman();
				opeForeman.setFactory(operation.getFab());
				String ope_id = operation.getOperation_id();
				Code code= codeService.getCode(ope_id);
				if(code!=null ){
					Long id =code.getId(); 
					opeForeman.setOpe_fk(id);
				}
				opeForeman.setOpe_id(ope_id);
				opeForeman.setForeman_id(operation.getUser_id());
				opeForeman.setForeman_name(operation.getUserName());
				opeForeman.setDepartment_id(operation.getDepartment_id());
				opeForeman.setDepartment_name(operation.getDeptName_s());
				operationForemanManager.save(opeForeman);

		}
		logger.info("同步站点和领班end");
	}
	
}
